import requests
import json
from user.redis_tools import RedisCache
from user.config import APPID, APPSECRET, WEIXIN_REDIS_KEY_PREFIX

r = RedisCache()

wx_urls = {
    "get_access_token": "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}",
    "push_template_msg": "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={}",
    "get_user_list": "https://api.weixin.qq.com/cgi-bin/user/get?access_token={}&next_openid={}",
    "get_user_info": "https://api.weixin.qq.com/cgi-bin/user/info?access_token={}&openid={}&lang=zh_CN",
    "create_menu": "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={}",
    "get_qrcode_ticket": "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={}",
    "show_qrcode": "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={}"
}

post_header = {'Content-Type': 'application/json', 'encoding': 'utf-8'}


def access_token_to_redis(access_token):
    key = WEIXIN_REDIS_KEY_PREFIX + "accessToken"
    r.set(key, access_token, ex=7200)
    return key


def get_access_token_from_wx():
    url = wx_urls["get_access_token"].format(APPID, APPSECRET)
    response = requests.get(url)
    access_token = json.loads(response.text)['access_token']
    access_token_to_redis(access_token)
    return access_token


def get_access_token_from_redis():
    access_token = r.get("weixin:accessToken")["result"]
    if access_token is None:
        access_token = get_access_token_from_wx()
    return access_token


def get_user_list(next_openid=""):
    access_token = get_access_token_from_redis()
    response = requests.get(wx_urls["get_user_list"].format(access_token, next_openid))
    return json.loads(response.text)


def get_user_info(openid):
    access_token = get_access_token_from_redis()
    response = requests.get(wx_urls["get_user_info"].format(access_token, openid))
    return json.loads(response.text)


def push_template_msg(json_data):
    access_token = get_access_token_from_redis()
    url = wx_urls["push_template_msg"].format(access_token)
    response = requests.post(url, data=json.dumps(json_data), headers=post_header)
    return json.loads(response.text)


def create_qrcode(json_data):
    access_token = get_access_token_from_redis()
    response = requests.post(wx_urls["get_qrcode_ticket"].format(access_token), data=json.dumps(json_data), headers=post_header)
    response_data = json.loads(response.text)
    ticket = response_data['ticket']
    return wx_urls["show_qrcode"].format(ticket)
